//
//  CNBBSViewController.m
//  CsdnPlus
//
//  Created by 孟瑞瑞 on 2018/5/7.
//  Copyright © 2018年 CSDN. All rights reserved.
//

#import "CNBBSViewController.h"
#import "CNBBSContentViewController.h"
#import "CNBBSForumListViewModel.h"
#import "CNBBSSectionViewController.h"
#import "CNBBSPostedViewController.h"
#import "CNBBSNetManager.h"
#import <CNBaseViewTool/CNLoadingGifView.h>
#import <FFRouter/FFRouter.h>
#import <CNBaseTool/CNCategoryHeader.h>
#import <CNBaseViewTool/CNNoDataView.h>
#import <CNBaseViewTool/UIView+CNEmpty.h>
#import <CNBaseViewTool/CNRefreshGifHeader.h>
#import <CNBaseViewTool/CNRefreshAutoNormalFooter.h>
#import <CNBaseViewTool/CNViewConst.h>

@interface CNBBSViewController ()<WMPageControllerDataSource,WMPageControllerDelegate>

@property (nonatomic, strong) NSMutableArray *bbsSectionArray;

@property (nonatomic, strong) NSMutableArray *bbsTopiceTypeArray;

@property (nonatomic, strong) NSMutableArray *isTechArray;

@property (nonatomic, strong) CNBBSForumListViewModel *forumVM;

@property (nonatomic, strong) NSArray *isFavoritedNameArray;

@property (nonatomic, strong) UIButton *postbbsBtn;

@property (nonatomic, strong) UILabel *taskRedLabel;

@property (nonatomic, strong) CNBBSForumListViewModel *taskVM;

@property (nonatomic, strong)CNLoadingGifView *loadingView;

@property (nonatomic, assign) BOOL shouldHide;
@end

@implementation CNBBSViewController

+ (void)load{
     [FFRouter registerRouteURL:[CNRoutePath appUrlWithRoutePath:CNBBSListPageRoute] handler:^(NSDictionary *routerParameters) {
           CNBBSViewController *vc = [[CNBBSViewController alloc]init];
           [(UINavigationController *)routerParameters[@"nav"] pushViewController:vc animated:YES];
       }];
}

-(CNBBSForumListViewModel *)forumVM
{
    if (!_forumVM) {
        _forumVM = [[CNBBSForumListViewModel alloc]init];
    }
    return _forumVM;
}

-(CNBBSForumListViewModel *)taskVM
{
    if (!_taskVM) {
        _taskVM = [[CNBBSForumListViewModel alloc]init];
    }
    return _taskVM;
}

-(NSMutableArray *)bbsSectionArray
{
    if (!_bbsSectionArray) {
        _bbsSectionArray = [[NSMutableArray alloc]init];
        [_bbsSectionArray addObjectsFromArray:@[@"技术区",@"生活区"]];
    }
    return _bbsSectionArray;
}

-(NSMutableArray *)bbsTopiceTypeArray
{
    if (!_bbsTopiceTypeArray) {
        _bbsTopiceTypeArray = [[NSMutableArray alloc]init];
        [_bbsTopiceTypeArray addObjectsFromArray:@[@"tech",@"nontech"]];
    }
    return _bbsTopiceTypeArray;
}

-(NSMutableArray *)isTechArray
{
    if (!_isTechArray) {
        _isTechArray = [[NSMutableArray alloc]init];
         [_isTechArray addObjectsFromArray:@[@(YES),@(NO)]];
    }
    return _isTechArray;
}
- (CNLoadingGifView *)loadingView{
    if (!_loadingView) {
        _loadingView = [[CNLoadingGifView alloc]init];
        [self.view addSubview:_loadingView];
        [_loadingView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.mas_equalTo(self.view);
        }];
    }
    return _loadingView;
}

-(instancetype)init
{
    if (self = [super init]) {
        //self.showOnNavigationBar = YES;
        self.menuViewStyle = 1;
        self.progressViewIsNaughty = YES;
        self.menuViewLayoutMode = WMMenuViewLayoutModeLeft;
        self.progressViewBottomSpace = 4;
        self.progressHeight = 2;
        self.progressWidth = 24;
        self.itemMargin = 16;
        self.progressColor = naviBGColor; 
        
        self.itemMargin = 20;
        //选中颜色和未选中颜色
        self.titleColorNormal = cellDesTitleTextColor;
        if ([CNThemesManager isNight])
        {
            self.titleColorSelected = slideBarTextSelectColor;
        }
        else
        {
            self.titleColorSelected = navigationBarTitleColor;
        }
        // 未选中的字号
        self.titleSizeNormal = 17;
        // 选中的字号
        self.titleSizeSelected = 17;
        
        [self updateItemMargins];
        self.titleFontSelected = [UIFont systemFontOfSize:17 weight:(UIFontWeightMedium)];
        self.titleFontNormal = [UIFont systemFontOfSize:17 weight:(UIFontWeightRegular)];
        
        self.bounces = YES;
        
        self.delegate = self;
        self.dataSource = self;
        self.automaticallyCalculatesItemWidths = YES;
        //self.titleFontName = @"PingFangSC-Semibold";
        //self.titleFontName = @"PingFangSC-Regular";
        self.delegate = self;
        self.dataSource = self;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.edgesForExtendedLayout = UIRectEdgeNone;
    self.navigationItem.title = @"论坛";
    if (self.navigationController.viewControllers.count != 1) {
      [Factory addBlackItemToVC:self];
    }
    self.view.theme_backgroundColor = menuPageBGColorPicker;
    self.menuView.theme_backgroundColor = menuPageBGColorPicker;
    [self addConfigBBSSectionOrTaskBtn];
    [self changeSkin];
    self.loadingView.hidden = NO;
    [self refreshData];
//    self.menuView.layer.theme_shadowColor = shadowsColorPicker;
//    self.menuView.layer.shadowOffset = CGSizeMake(0, 0.5);
//    self.menuView.layer.shadowOpacity = [CNThemesManager isNight]?1:0.15;
//    self.menuView.layer.shadowRadius = 0;
    
    //监听更换皮肤通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeSkin) name:CNThemeUpdateNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideLoading) name:@"hideLoading" object:nil];
}

-(void)changeSkin
{
    self.titleColorNormal = cellDesNightTitleTextColor;
    self.titleColorSelected = [CNThemesManager isNight]? slideBarTextSelectColor:navigationBarTitleColor;
    self.scrollView.theme_backgroundColor = pageBGColorPicker;
    [self reloadData];
    [self addPostSuspensionButton];
//    self.menuView.layer.shadowOpacity = [CNThemesManager isNight]?1:0.15;
}

//导航栏隐藏后设置状态栏颜色
- (UIStatusBarStyle)preferredStatusBarStyle
{
    if ([CNThemesManager isNight])
    {
        return UIStatusBarStyleLightContent;
    }
    else
    {
        return UIStatusBarStyleDefault;
        
    }
    return UIStatusBarStyleDefault;
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //发送关注列表文章更新通知
//    [[NSNotificationCenter defaultCenter] postNotificationName:CNHasNewArticleNotification object:nil];
    [self getTaskCount];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
}
- (void)hideLoading{
    if (self.shouldHide) {
        self.loadingView.hidden = YES;
    }
}

-(void)getTaskCount
{
    if ([CNViewConst isLogin]) {
        [self.taskVM getBBSTaskCountCompletionHandle:^(NSError *error) {
            if (!error) {
                if (self.taskVM.code == 200) {
                    if (self.taskVM.taskCount > 0) {
                        self.taskRedLabel.hidden = NO;
                    }else{
                        self.taskRedLabel.hidden = YES;
                    }
                }else{
                    self.taskRedLabel.hidden = YES;
                }
            }else{
                self.taskRedLabel.hidden = YES;
            }
        }];
    }else{
        self.taskRedLabel.hidden = YES;
    }
}

#pragma mark - 获取数据
//刷新数据
- (void)refreshData
{
    [self.view bringSubviewToFront:self.loadingView];
    [self.forumVM getDataFromNetCompleteHandle:^(NSError *error) {
        
        if (!error)
        {
            if (self.forumVM.code == 200)
            {
                if (![self.isFavoritedNameArray isEqualToArray:self.forumVM.isFavoritedNameArray])
                {
                    [self.bbsSectionArray removeAllObjects];
                    [self.bbsTopiceTypeArray removeAllObjects];
                    [self.isTechArray removeAllObjects];
                    
                    //AF的回调 是在主线程中
                    [self.bbsSectionArray addObjectsFromArray:@[@"技术区",@"生活区"]];
                    [self.bbsTopiceTypeArray addObjectsFromArray:@[@"tech",@"nontech"]];
                    [self.isTechArray addObjectsFromArray:@[@(YES),@(NO)]];
                    self.isFavoritedNameArray = self.forumVM.isFavoritedNameArray;
                    [self.bbsSectionArray addObjectsFromArray:self.forumVM.isFavoritedNameArray];
                    [self.bbsTopiceTypeArray addObjectsFromArray:self.forumVM.isFavoritedUrlnameArray];
                    [self.isTechArray addObjectsFromArray:self.forumVM.isFavoritedTechForumArray];
                    [self updateItemMargins];
                    [self reloadData];
                    [self addPostSuspensionButton];
                    self.shouldHide = YES;
                }
            }
            else
            {
                [self showErrorMsg:@"加载失败，请稍后再试"];
            }
            
        }else{
            [self showError:error];;
        }
    }];
    
}
- (void)updateItemMargins{
    NSMutableArray *itemMarginArray = [NSMutableArray array];
    for (int i = 0; i < self.bbsSectionArray.count + 1; i++) {
        if (i == 0) {
            [itemMarginArray addObject:@(16)];
            
        }else{
            [itemMarginArray addObject:@(20)];
        }
    }
    self.itemsMargins = [NSArray arrayWithArray:itemMarginArray];
}
#pragma mark - configPageVC
- (void)configBBSSectionOrTaskWithUrl:(NSString *)url
{
    UIView *rightView = [[UIView alloc]init];
    rightView.frame = CGRectMake(0, 0,85,44);
    UIButton *addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [addBtn theme_setImage:addChannelImage forState:(UIControlStateNormal)];
    [addBtn theme_setImage:addChannelImage forState:(UIControlStateHighlighted)];
    addBtn.frame = CGRectMake(5, 0,40,44);
    addBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 16);

    addBtn.centerY = rightView.centerY;
    addBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    //添加添加版块按钮
    [rightView addSubview:addBtn];
    
    @weakify(self);
   
    [addBtn bk_addEventHandler:^(id sender) {
        @strongify(self);
        if ([CNViewConst isLogin])
        {
            DDLogDebug(@"登录了");
            CNBBSSectionViewController *sectionVC = [[CNBBSSectionViewController alloc]init];
            sectionVC.block = ^{
                [self refreshData];
            };
            
            [self.navigationController pushViewController:sectionVC animated:YES];
        }
        else
        {
            [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
        }
    } forControlEvents:(UIControlEventTouchUpInside)];
    
    UIButton *taskBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [taskBtn theme_setImage:taskbbsImage forState:(UIControlStateNormal)];
    [taskBtn theme_setImage:taskbbsImage forState:(UIControlStateHighlighted)];
    taskBtn.frame = CGRectMake(45, 0,40,44);
    taskBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 16);
    taskBtn.centerY = rightView.centerY;
    taskBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    self.taskRedLabel = [[UILabel alloc]init];
    _taskRedLabel.theme_backgroundColor = pageBGColorPicker;
    _taskRedLabel.layer.cornerRadius = 6;
    _taskRedLabel.layer.masksToBounds = YES;
    [taskBtn addSubview:_taskRedLabel];
    [_taskRedLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(12, 12));
        make.right.mas_equalTo(taskBtn.mas_right).mas_equalTo(-12);
        make.bottom.mas_equalTo(taskBtn.mas_top).mas_equalTo(20);
    }];
    UILabel *redLb = [[UILabel alloc]init];
    redLb.theme_backgroundColor = naviBGColorPicker;
    redLb.layer.cornerRadius = 5;
    redLb.layer.masksToBounds = YES;
    [self.taskRedLabel addSubview:redLb];
    [redLb mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(10, 10));
        make.center.mas_equalTo(0);
    }];
    
    //添加发帖按钮
    [rightView addSubview:taskBtn];
    
    [taskBtn bk_addEventHandler:^(id sender) {
        @strongify(self);
        if ([CNViewConst isLogin]){
          [CNRouteTool routeUrl:url navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"bbs" exts:@{}];
        }else{
          [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
       }
    } forControlEvents:UIControlEventTouchUpInside];
    
    self.menuView.rightView = rightView;
}

- (void)configBBSSection
{
    UIView *rightView = [[UIView alloc]init];
    rightView.frame = CGRectMake(0, 0,45,44);
    UIButton *addBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [addBtn theme_setImage:addChannelImage forState:(UIControlStateNormal)];
    [addBtn theme_setImage:addChannelImage forState:(UIControlStateHighlighted)];
    addBtn.frame = CGRectMake(5, 0,40,44);
    addBtn.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, 16);

    addBtn.centerY = rightView.centerY;
    addBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    //添加添加版块按钮
    [rightView addSubview:addBtn];
    
    @weakify(self);
    [addBtn bk_addEventHandler:^(id sender) {
        @strongify(self);
        if ([CNViewConst isLogin])
        {
            CNBBSSectionViewController *sectionVC = [[CNBBSSectionViewController alloc]init];
            sectionVC.block = ^{
                [self refreshData];
            };
            
            [self.navigationController pushViewController:sectionVC animated:YES];
        }else{
            [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
        }
    } forControlEvents:(UIControlEventTouchUpInside)];
    
    
    self.menuView.rightView = rightView;
}

-(void)addConfigBBSSectionOrTaskBtn
{
    [CNBBSNetManager getCsdnSelectKVWithKey:@"BBS_TASK" completionHandle:^(CNBBSApolloModel *model, NSError *error) {
        if (!error) {
            if (model.code == 200 && [model.data.BBS_TASK.url isValid]) {
                [self configBBSSectionOrTaskWithUrl:model.data.BBS_TASK.url];
            }else{
                [self configBBSSection];
            }
        }else{
            [self configBBSSection];
        }
    }];
}

//添加发布悬浮按钮
-(void)addPostSuspensionButton
{
    if (!self.postbbsBtn) {
        UIButton *postBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        self.postbbsBtn = postBtn;
        postBtn.theme_backgroundColor = naviBGColorPicker;
        [postBtn setImage:[UIImage imageNamed:@"blinkPost"] forState:(UIControlStateNormal)];
        [postBtn setImage:[UIImage imageNamed:@"blinkPost"] forState:(UIControlStateHighlighted)];
//        postBtn.layer.masksToBounds = YES;
        postBtn.layer.cornerRadius = 24;
        postBtn.layer.shadowOffset = CGSizeMake(0, 3);
        postBtn.layer.shadowRadius = 4;
        postBtn.layer.shadowColor = [UIColor colorFromHexCode:@"#D92E2E" andAlpha:0.3].CGColor;
        postBtn.layer.shadowOpacity = 1.0;
        [self.view addSubview:postBtn];
        [postBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(-24);
            make.right.mas_equalTo(-24);
            make.size.mas_equalTo(CGSizeMake(48, 48));
        }];
        @weakify(self)
        [postBtn bk_addEventHandler:^(id sender) {
            @strongify(self);
            if ([CNViewConst isLogin]){
              CNBBSPostedViewController *postVC = [[CNBBSPostedViewController alloc]init];
              [self.navigationController pushViewController:postVC animated:YES];
            } else{
                [CNRouteTool routeUrl:[CNRoutePath appUrlWithRoutePath:CNLoginQuickRoute] navigationVc:self.navigationController refer:@"" trackingCode:@"" urlParams:@{} vipReferrer:@"" exts:@{}];
          }
        } forControlEvents:UIControlEventTouchUpInside];
    }
    [self.view bringSubviewToFront:self.postbbsBtn];
}

#pragma mark - WMPageController 的代理方法
- (NSInteger)numbersOfChildControllersInPageController:(WMPageController *)pageController {
    if (self.bbsSectionArray.count == 0 || !self.bbsSectionArray ) {
        return 0;
    }
    return self.bbsSectionArray.count; 
}

- (__kindof UIViewController *)pageController:(WMPageController *)pageController viewControllerAtIndex:(NSInteger)index {
    pageController.scrollView.theme_backgroundColor = searchPageBGColorPicker;
    if (index > self.bbsSectionArray.count) {
        return  [[CNBBSContentViewController alloc]init];
    }
    CNBBSContentViewController *bbsVc = [[CNBBSContentViewController alloc]init];
    bbsVc.topiceType = self.bbsTopiceTypeArray[index];
    bbsVc.isTech = [self.isTechArray[index] boolValue];
    bbsVc.titleName = self.bbsSectionArray[index];

    return bbsVc;
}

- (NSString *)pageController:(WMPageController *)pageController titleAtIndex:(NSInteger)index {
    
    return self.bbsSectionArray[index];
    
}

- (CGRect)pageController:(WMPageController *)pageController preferredFrameForMenuView:(WMMenuView *)menuView {
    
    return CGRectMake(0, 0, kWindowW, 44);
}

- (CGRect)pageController:(WMPageController *)pageController preferredFrameForContentView:(WMScrollView *)contentView {
    
    CGFloat originY = CGRectGetMaxY([self pageController:pageController preferredFrameForMenuView:self.menuView]);
    
    return CGRectMake(0, originY, self.view.frame.size.width, self.view.frame.size.height - originY);
}

#pragma mark - 需要刷新
- (void)needRefreshTableViewData
{
    CNBBSContentViewController *bbsVC = (CNBBSContentViewController *)self.currentViewController;
    [bbsVC headerRefresh];
}


#pragma mark - WMMenuView 的代理方法
- (void)menuView:(WMMenuView *)menu didSelesctedIndex:(NSInteger)index currentIndex:(NSInteger)currentIndex {
    if (index == -1) {
        [self needRefreshTableViewData];
    }else {
        [super menuView:menu didSelesctedIndex:index currentIndex:currentIndex];
    }
}

-(void)dealloc
{
    //在页面消失的回调方法中移除通知。
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
